# encoding: utf-8
# !/usr/local/bin/python3

"""
@author: Gao Shuo
@contact: dorothy400@163.com
@software: PyCharm
@file: concat_test_file.py
@time: 2020/5/15 10:45

input: 
output: 
"""


import os.path
import sys

from PIL import Image



if __name__ == "__main__":
    ext = ".png"
    clip_width = 800
    clip_height = 400
    path_ori = sys.argv[1]
    dest = sys.argv[2]
    all_names = os.listdir(path_ori)
    img_names = [x.split('.jpg')[0] for x in all_names]
    img_names = list(set(img_names)) # unique
    for img_name in img_names:
        print "Now processing " + img_name
        all_clipped = [x for x in all_names if x.split('.jpg')[0] == img_name]
        all_i = [int(x.split('_')[4]) for x in all_clipped]
        # all_i = list(set(all_i))  # unique
        all_i.sort()
        all_j = [int(x.split('_')[5].split('.')[0]) for x in all_clipped]
        # all_j = list(set(all_j))  # unique
        all_j.sort()
        width = max(all_i) # 原图的长宽
        height = max(all_j)
        target = Image.new('RGB', (width, height))
        for img_clipped in all_clipped:
            # print img_clipped
            str_xy = img_clipped.split('.jpg')[1]
            xy = (int(str_xy.split('_')[1]),int(str_xy.split('_')[2]),
                  int(str_xy.split('_')[3]),int(str_xy.split('_')[4].split('.png')[0]) )
            image = Image.open(os.path.join(path_ori, img_clipped))
            target.paste(image, xy)
        target.save(dest + '/' + img_name + ext, quality=100)



